import React, { Component } from 'react';
import { Link } from 'react-router-dom';
import classnames from 'classnames';
import { addCartFetch, addWish, delWish } from 'shared/commonFetch/index';
import toFixed from 'shared/utils/toFixed';
import './index.less';

class ProductItem extends Component {

  handleChangeWish(item, e) {
    e.persist();
    const { product_id } = item;
    const type = e.target.textContent;
    const { onChangeWish, iswishPage } = this.props;
    gloablMonitor(['商品列表页-关注', item.title])
    if (type == '取消关注') {
      delWish(product_id).then((res) => {
        if(res.code === 1000){
          onChangeWish && onChangeWish(item);
          if(!iswishPage) {
            e.target.textContent = '关注';
            e.target.style.backgroundColor = '#fff';
            e.target.style.color = '#666';
          }
        }
      });
    } else {
      const promiseAddWish= addWish(product_id)
      promiseAddWish && promiseAddWish.then((res) => {
        if(res.code === 1000){
          e.target.textContent = '取消关注';
          e.target.style.backgroundColor = '#E21B23';
          e.target.style.color = '#fff';
        }
      });
    }
  }

  render() {
    const { data = {}, iswishPage } = this.props;
    const cls = classnames({
      'item-focus':true,
      'wish-color':data.iswishlist || iswishPage
    })
    return (
      <div className="product-list-main">
        <div className="product-list-main-item">
          <Link className="imgbox" to={`/ProductDetail/${data.product_id}/buyProductDetail`}>
            <img src={data.image} alt="" />
          </Link>
          <div className="item-info">
            <div className="item-info-container">
              <div className="item-info-name">
                <span>
                  <Link to={`/ProductDetail/${data.product_id}/buyProductDetail`}>{data.title}</Link>
                </span>
              </div>
              <div className="item-info-tag">
                {
                  data.tags && data.tags.length > 0 && data.tags.map((item,i)=><div key={i}>{item}</div>)
                }
              </div>
            </div>
            <div className="item-info-ctrl">
              <span className="item-price">￥{toFixed(data.price)}</span>
              <span
                className={cls}
                onClick={(e) => this.handleChangeWish(data, e)}
              >
                {data.iswishlist || iswishPage ? '取消关注' : '关注'}
              </span>
              <span
                className="item-join"
                onClick={() => {
                  gloablMonitor(['商品列表页-加入购物车', data.title])
                  addCartFetch(data.product_id, 1)
                }}
              >
              加入购物车

              </span>
            </div>
          </div>
        </div>
      </div>
    );
  }
}

export default ProductItem;
